package spring.data.jpa.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import spring.data.jpa.entity.Department;
import spring.data.jpa.entity.Employee;
import spring.data.jpa.repository.DepartmentRepository;
import spring.data.jpa.repository.support.JpaSearchSupport;
import spring.data.jpa.repository.support.SearchFilter.Operator;
import spring.data.jpa.tools.DBHelper;

@Service
public class DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;

    public List<Department> findAll() {
        return departmentRepository.findByParams();
    }

    public List<Department> findByParams(String name) {
        return departmentRepository.findByParams(name, PageRequest.of(1, 2));
    }

    public List<Department> findBy(Department dept, String name) {
        return departmentRepository.findByParams(dept, name, PageRequest.of(1, 2));
    }

    public List<Department> findBy(Department dept, Employee emp) {
        return departmentRepository.findByEmployeeExist(dept, emp);
    }

    public List<Department> findByJpql(Department dept) {
        return departmentRepository.findByEmployeeExistJpql(dept.getName());
    }

    public List<Department> findByParams(String name, int number) {
        return departmentRepository.findByParams("%" + name + "%", number);
    }
    
    public List<Department> findByParamIndex(String name, int number) {
        return departmentRepository.findByParameterList(name);
    }

    @Transactional
    public void save(Department entity) {
        departmentRepository.save(entity);
    }

    @Transactional
    public void saveBy(Department dept) {
        departmentRepository.addDept(dept);
    }

    public Department get(Long id) {
        return departmentRepository.getOne(id);
    }

    public List<Department> findBy(String field, Object value) {
        return departmentRepository.findAll(DBHelper.newSpecification(Department.class).build(field, value, Operator.EQ).specification());
    }

    public List<Department> findAll(JpaSearchSupport searchDefinition) {
        return departmentRepository.findAll(DBHelper.buildSpecification(searchDefinition, Department.class));
    }

    public List<Department> findAll(Map<String, Object> searchParams) {
        return departmentRepository.findAll(DBHelper.buildSpecification(searchParams, Department.class));
    }
}
